<template>
  <div id="home">
    <nav-bar class="home-nav"><div slot="center">购物街</div></nav-bar>
    <tab-control :titles="['流行','新款','精选']"
                 @tabClick="tabClick"
                 ref="tabControl1"
                 class="tab-control"
                 v-show="isTabFixed">
    </tab-control>
    <scroll class="content"
            ref="scroll"
            :probe-type="3"
            @scroll="contentScroll"
            :pull-up-load="true"
            @pullingUp="loadMore">
      <home-swiper :banners="banners" @swiperImageLoad="swiperImageLoad"></home-swiper>
      <home-recommend-view :recommends="recommends"></home-recommend-view>
      <home-feature-view></home-feature-view>
      <tab-control :titles="['流行','新款','精选']"
                   @tabClick="tabClick"
                   ref="tabControl2">
      </tab-control>
      <goods-list :goods="showGoods"></goods-list>
    </scroll>
    <back-top @click.native="backClick" v-show="isShowBackTop"></back-top>
  </div>
</template>

<script>
  import NavBar from "components/common/navbar/NavBar";
  import TabControl from "components/content/tabControl/TabControl";
  import GoodsList from "components/content/goods/GoodsList";
  import Scroll from "components/common/scroll/Scroll";
  import BackTop from "components/content/backTop/BackTop";

  import HomeSwiper from "./childComps/HomeSwiper";
  import HomeRecommendView from "./childComps/HomeRecommendView";
  import HomeFeatureView from "./childComps/HomeFeatureView";

  import {getHomeMultidata,
          getHomeGoods} from "network/home";
  // import {debounce} from "common/utils";
  import {itemListenerMixin} from "common/mixin";

  export default {
    name: "Home",
    components:{
      NavBar,
      HomeSwiper,
      HomeRecommendView,
      HomeFeatureView,
      TabControl,
      GoodsList,
      Scroll,
      BackTop
    },
    data() {
      return{
        banners: [],
        recommends: [],
        goods: {
          'pop' : {page: 0, list : []},
          'new' : {page: 0, list : []},
          'sell' : {page: 0, list : []}
        },
        currentType: 'pop',
        isShowBackTop: false,
        // tabControl吸顶操作
        tabOffsetTop: 0,
        // 默认情况下不要吸顶
        isTabFixed: false,
        // 离开页面的时候保存页面的位置
        saveY: 0,
        // // 离开首页后不需要在监听itemload
        // itemImgListener: null
      }
    },
    computed: {
      showGoods() {
        return this.goods[this.currentType].list
      }
    },
    mixins: [itemListenerMixin],
    created() {
      //1.请求多个数据
      this.getHomeMultidata()
      //2.请求商品数据
      this.getHomeGoods('pop')
      this.getHomeGoods('new')
      this.getHomeGoods('sell')
    },
    mounted() {
      // 1.图片加载完成的事件监听，主要是滑动较卡
      //使用防抖动函数防止一直使用refresh
      // const newRefresh = debounce(this.$refs.scroll.refresh, 100)
      // // 监听item中图片加载完成
      // this.itemImgListener = () => {newRefresh()}
      // this.$bus.$on('itemImageLoad', () => {
      //   newRefresh()
      // })
      // 2.获取tabControl的offsetTop
      // 我们想要拿tabControl组件的元素
      // 所有组件都有一个元素$el: 用于获取组件元素
      // 现在offsetTop不是最终的，只是挂在上去，有时候图片还没加载完，所以我们要监听图片都加载完在计算
      // 要监听轮播图加载完成
      // this.tabOffsetTop = this.$refs.tabControl.$el.offsetTop
    },
    destroyed() {

    },
    activated() {
      this.$refs.scroll.refresh()
      this.$refs.scroll.scrollTo(0, this.saveY, 0)
    },
    deactivated() {
      // 1.保存y值
      this.saveY = this.$refs.scroll.getScrollY()
      // console.log(this.saveY);
      // 2.取消全局事件的监听
      this.$bus.$off("itemImageLoad", this.itemImgListener)
    },
    methods: {
      // 网络请求相关方法
      getHomeMultidata() {
        getHomeMultidata().then(res => {
          // console.log(res); // 函数执行结束res就会被回收，所以我们要保存下来
          this.banners = res.data.banner.list;
          this.recommends = res.data.recommend.list;
        })
      },
      getHomeGoods(type) {
        const page = this.goods[type].page + 1
        getHomeGoods(type, page).then( res => {
          // console.log(res)
          // 返回的是pop的第一页的30行数据
          this.goods[type].list.push(...res.data.list)
          this.goods[type].page += 1
          // // 上拉加载结束后继续调用，不然只能拉一次
          this.$refs.scroll.finishPullUp()

        })
      },
      // 事件监听相关方法
      tabClick(index) {
        switch (index) {
          case 0:
            this.currentType = 'pop'
            break
          case 1:
            this.currentType = 'new'
            break
          case 2:
            this.currentType = 'sell'
        }
        this.$refs.tabControl1.currentIndex = index
        this.$refs.tabControl2.currentIndex = index
      },
      backClick(){
        this.$refs.scroll.scrollTo(0,0,500)
      },
      contentScroll(position) {
        // 1.判断BackTop是否显示
        this.isShowBackTop = -position.y > 1000
        // 2. 决定tabControl是否吸顶（position : fixed）
        this.isTabFixed = (-position.y) > this.tabOffsetTop
      },
      loadMore() {
        this.getHomeGoods(this.currentType)
      },
      swiperImageLoad() {
        this.tabOffsetTop = this.$refs.tabControl2.$el.offsetTop
      }
      /*debounce(func, delay) {*/
      //   let timer = null
      //   // timer表示有没有延时器
      //   return function (...args) {
      //     if(timer) clearTimeout(timer)
      //     timer = setTimeout(() => {
      //       // apply(this指向，第二个参数是数组或对象，将单独参数传给func函数)
      //       func.apply(this, args)
      //     }, delay)
      //   }
      //
      // }
    }
  }
</script>

<style scoped>
  #home {
    /*padding-top: 44px;*/
    height: 100vh;
    position: relative;
  }

  .home-nav {
    background-color: var(--color-tint);
    color: #ffffff;

    /*position: sticky;*/
    /*top: 0px;*/
    /*z-index: 9;*/
  }

  .content {
    overflow: hidden;
    position: absolute;
    top: 44px;
    bottom: 49px;
    left: 0;
    right: 0;
  }

  .tab-control {
    position: relative;
    z-index: 9;
  }
  /*.fixed {*/
  /*  position: fixed;*/
  /*  left: 0;*/
  /*  right: 0;*/
  /*  top: 44px;*/
  /*}*/
</style>
